package com.ygqh.baby.service.impl;

import com.ygqh.baby.ao.AppType;
import com.ygqh.baby.ao.BusinessModule;
import com.ygqh.baby.exception.YgHttpException;
import com.ygqh.baby.model.YgShoppingCarModel;
import com.ygqh.baby.po.YgOrder;
import com.ygqh.baby.po.YgOrderPayment;
import com.ygqh.baby.service.TrustoneService;
import com.ygqh.baby.service.YgOrderPaymentService;
import com.ygqh.baby.service.YgOrderService;
import com.ygqh.baby.service.trustone.TrustoneApi;
import com.ygqh.baby.service.trustone.YgCustomsApi;
import com.ygqh.baby.service.trustone.model.ApiResult;
import com.ygqh.baby.service.trustone.model.TruStoneAddOrderReq;
import com.ygqh.baby.service.trustone.model.YgDeclareCustomsResult;
import com.ygqh.baby.utils.ExceptionUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service
public class TrustoneServiceImpl implements TrustoneService {

    private Logger logger = LoggerFactory.getLogger(getClass());
    @Value("${trustoner.supplier.id}")
    private Long TRUSTONE_SUPPLIER_ID;
    @Autowired
    private YgOrderService ygOrderService;
    @Autowired
    private TrustoneApi trustoneApi;
    @Autowired
    private YgCustomsApi ygCustomsApi;
    @Autowired
    private YgOrderPaymentService ygOrderPaymentService;

    private final static ExecutorService executorService = Executors.newFixedThreadPool(3);

    @Override
    public Boolean validateIsTrustonerOrder(List<YgShoppingCarModel> carModelList) {
        if (CollectionUtils.isEmpty(carModelList)) {
            return Boolean.FALSE;
        }
        for (YgShoppingCarModel carModel : carModelList) {
            if (carModel.getSupplierId().equals(TRUSTONE_SUPPLIER_ID)) {
                return Boolean.TRUE;
            }
        }
        return Boolean.FALSE;
    }

    @Override
    public Boolean isTrustonerOrder(List<Long> supplierIds) {
        if (CollectionUtils.isEmpty(supplierIds)) {
            return Boolean.FALSE;
        }
        return supplierIds.stream().anyMatch(id -> id.equals(TRUSTONE_SUPPLIER_ID));
    }

    @Override
    public void pushTrustonerOrderAndDeclareCustoms(Long orderId) {
        doPushTrustonerOrderAndDeclareCustoms(orderId);
    }

    @Override
    public YgDeclareCustomsResult customDelarereDeclareByWx(String orderPayCode, AppType payAppType) {
        return ygCustomsApi.customDelarereDeclareByWx(orderPayCode, payAppType);
    }

    @Override
    public YgDeclareCustomsResult customDelarereModifyByWx(String orderPayCode, String transactionId, AppType payAppType) {
        return ygCustomsApi.customDelarereModifyByWx(orderPayCode, transactionId, payAppType);
    }

    @Override
    public ApiResult cancelorder(String orderId, String reason) throws YgHttpException {
        return trustoneApi.cancelorder(orderId, reason);
    }

    private void doPushTrustonerOrderAndDeclareCustoms(Long orderId) {

        executorService.execute(() -> {
            try {
                //TODO 折中方案；订单了过多时，堵塞过多
                System.out.println("6秒后进行报关，orderId:" + orderId);
                Thread.sleep(6000);
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
            YgOrder order = ygOrderService.findOrderDetailByOrderIdForThird(orderId);
            if (!order.getSupplierId().equals(TRUSTONE_SUPPLIER_ID)) {
                return;
            }
            if (order.getWdtOrderCode().startsWith("Tru")) {
                logger.info("重复推送。");
                return;
            }
            try {
                TruStoneAddOrderReq req = new TruStoneAddOrderReq();
                req.setOrder(order);
                YgOrderPayment payment = ygOrderPaymentService.findByOrderId(orderId.toString(), BusinessModule.DeclareCustoms);
                if (payment == null) {
                    YgDeclareCustomsResult declareCustoms = ygCustomsApi.declareCustoms(orderId, req.getIdentityNo(), order.getReceiver());
                    if (declareCustoms.getSuccess()) {
                        req.setOutTradeNo(declareCustoms.getOutTradeNo());
                        req.setTransactionId(declareCustoms.getTransactionId());
                        req.setPayType(declareCustoms.getPayType());
                        trustoneApi.trustoneAddOrder(req);
                    }
                } else {
                    req.setOutTradeNo(payment.getOrderPayCode());
                    req.setTransactionId(payment.getTransactionId());
                    req.setPayType(payment.getPayType());
                    trustoneApi.trustoneAddOrder(req);
                }
            } catch (Exception e) {
                logger.error("推送保税仓订单失败：orderId:{}>>>{}", ExceptionUtil.getExceptionMsg(e));
                e.printStackTrace();
            }
        });
    }
}
